package com.lf.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lf.constant.ConstantsValue;
import com.lf.entity.*;
import com.lf.entity.view.ViewUserResourceList;
import com.lf.enums.ErrorCodeEnum;
import com.lf.exception.ApiException;
import com.lf.jwt2admin.ITokenAdmin;
import com.lf.mapper.CustomerMapper;
import com.lf.mapper.MapperList;
import com.lf.service.ICustomerService;
import com.lf.util.MD5;
import com.lf.util.RowBoundUtil;
import com.lf.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CustomerServiceImpl extends MapperList implements ICustomerService {

    /**
     * 获取权限用户列表
     *
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper getRelationUsers() {
        List<SysUser> sysUsers = sysUserMapper.selectAll();
        return ResponseWrapper.succeed(sysUsers);
    }

    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper addManager(String account, String password) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setAccount(account);
        SomeValEntity someValEntity = new SomeValEntity();
        someValEntity.setKey1("pkey");
        someValEntity = someValMapper.selectOne(someValEntity);
        String pkey = someValEntity.getValue1();
        password = MD5.MD5Encode(password+pkey);
        customerEntity.setPassword(password);
        customerEntity.setAuthJson(new JSONObject().toJSONString());
        customerMapper.insert(customerEntity);

        return ResponseWrapper.succeed();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public ResponseWrapper login(String account, String password) {

        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setAccount(account);//使用用户名查找
        customerEntity.setStatus(0);
        customerEntity = customerMapper.selectOne(customerEntity);
        if (customerEntity == null){//使用用户名查找时，用户不存在
            throw  new ApiException(ErrorCodeEnum.SW50.code(),ErrorCodeEnum.SW50.msg());
        }

        SomeValEntity someValEntity = new SomeValEntity();
        someValEntity.setKey1("pkey");
        someValEntity = someValMapper.selectOne(someValEntity);
        String pkey = someValEntity.getValue1();
        password = MD5.MD5Encode(password+pkey);
        if (!customerEntity.getPassword().equals(password)){
            throw  new ApiException(ErrorCodeEnum.SW30.code(),ErrorCodeEnum.SW30.msg());
        }


        Map<String, Object> clamis = new HashMap<>();
        clamis.put("id", customerEntity.getId());
        String token = tokenAdmin.createToken(customerEntity.getId(), String.valueOf(customerEntity.getId()), clamis).getToken();
        if(StringUtils.isNullStr(token)){
            throw new ApiException(ErrorCodeEnum.TK1003);
        }

        return ResponseWrapper.succeed(token);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public ResponseWrapper loginOut(Integer id) {
        String loginKey = ConstantsValue.TOKEN_MANAGER_KEY + id;
        if (redisService.hasKey(loginKey)){
            redisService.deleteString(loginKey);
        }
        return ResponseWrapper.succeed();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public ResponseWrapper getAuthority(Integer id) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(id);
        customerEntity.setStatus(0);
        customerEntity = customerMapper.selectOne(customerEntity);
        JSONObject jsonObject = JSONObject.parseObject(customerEntity.getAuthJson());
        return ResponseWrapper.succeed(jsonObject.getJSONArray("data"));
    }

    /**
     * 获取管理员信息
     *
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper getAdminInfo(Integer id) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(id);
        customerEntity = customerMapper.selectOne(customerEntity);
        return ResponseWrapper.succeed(customerEntity);
    }

    /**
     * 管理员更换密码
     *
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper updateAdminPass(Integer id, String oldPassword, String newPassword) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(id);
        customerEntity = customerMapper.selectOne(customerEntity);

        SomeValEntity someValEntity = new SomeValEntity();
        someValEntity.setKey1("pkey");
        someValEntity = someValMapper.selectOne(someValEntity);
        String pkey = someValEntity.getValue1();
        oldPassword = MD5.MD5Encode(oldPassword+pkey);

        if (!customerEntity.getPassword().equals(oldPassword)){
            throw new ApiException(ErrorCodeEnum.SW30);
        }

        newPassword = MD5.MD5Encode(newPassword + pkey);
        customerEntity.setPassword(newPassword);
        customerMapper.updateByPrimaryKey(customerEntity);

        return ResponseWrapper.succeed();
    }

    /**
     * 获取管理员列表
     *
     * @param page
     * @param limit
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper getManagers(Integer page, Integer limit) {
        CustomerEntity customerEntity = new CustomerEntity();

        int count = customerMapper.selectCount(customerEntity);

        Example example=new Example(CustomerEntity.class);
        example.setOrderByClause("id desc");

        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThan("id",0);

        RowBounds rowBounds = RowBoundUtil.getRowBounds(limit, page);
        List<CustomerEntity> customerEntities = customerMapper.selectByExampleAndRowBounds(example, rowBounds);

        return ResponseWrapper.succeed(count, customerEntities);
    }

    /**
     * 关联（权限）用户
     *
     * @param adminId
     * @param permId
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper relationUser(Integer adminId, Long permId) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(adminId);
        customerEntity = customerMapper.selectOne(customerEntity);
        customerEntity.setRelationUser(permId);

        SysUser sysUser = new SysUser();
        sysUser.setId(permId);
        sysUser = sysUserMapper.selectOne(sysUser);

        customerEntity.setRelationUserName(sysUser.getNickname());

        customerMapper.updateByPrimaryKey(customerEntity);

        return ResponseWrapper.succeed();
    }

    /**
     * 刷新权限
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper flushPerm() {

        List<CustomerEntity> customerEntities = customerMapper.selectAll();
        for (CustomerEntity entity : customerEntities){

            ViewUserResourceList viewUserResourceList = new ViewUserResourceList();
            viewUserResourceList.setId(Long.valueOf(entity.getId()));
            List<ViewUserResourceList> viewUserResourceLists = viewUserResourceListMapper.select(viewUserResourceList);

            String authjson = this.getAuthJson(viewUserResourceLists);

            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setId(entity.getId());
            customerEntity = customerMapper.selectOne(customerEntity);
            customerEntity.setAuthJson(authjson);
            customerMapper.updateByPrimaryKey(customerEntity);



        }
        return ResponseWrapper.succeed();
    }

    /**
     * return json
     * 格式如下：
     * //{
     * //    "code": 0
     * //    ,"msg": ""
     * //    ,"data": [{
     * //        "title": "数据管理"
     * //        ,"icon": "layui-icon-home"
     * //        ,"list": [{
     * //            "title": "平台统计"
     * //            ,"jump": "data/show"
     * //        }]
     * //    }]
     * //}
     */
    private String getAuthJson(List<ViewUserResourceList> viewUserResourceLists){
        JSONObject authJson = new JSONObject();
        authJson.put("code",0);
        authJson.put("msg","");
        JSONArray data = new JSONArray();
        for (ViewUserResourceList v1 : viewUserResourceLists){
            if ("menu".equals(v1.getType()) && !"JC-API".equals(v1.getName()) && (v1.getParentId() == null || v1.getParentId() == 0L)){
                Long pid = v1.getResourcesId();
//                log.info("权限类型:{},用户ID:{},权限名称:{},权限路径:{},排序:{},图标:{}",
//                        v1.getType(),v1.getId(),v1.getName(),v1.getUrl(),v1.getSort(),v1.getIcon());//这里处理用户权限

                JSONObject json1 = new JSONObject();
                json1.put("title",v1.getName().split("-")[1]);
                json1.put("icon",v1.getIcon());
                JSONArray list = new JSONArray();
                for (ViewUserResourceList v2 : viewUserResourceLists){
                    if ("menu".equals(v1.getType()) && v2.getParentId() == pid){
                        JSONObject json2 = new JSONObject();
                        json2.put("title",v2.getName().split("-")[1]);
                        json2.put("jump",v2.getUrl());
                        list.add(json2);
                    }
                }
                json1.put("list",list);
                data.add(json1);
            }

        }
        authJson.put("data",data);
        String restr = authJson.toJSONString();
        return restr;
    }

    /**
     * 更新管理员信息
     *
     * @param id
     * @param fullName
     * @param legalName
     * @param address
     * @param mobile
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public ResponseWrapper updateAdmin(Integer id, String fullName, String legalName, String address, String mobile) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(id);
        customerEntity = customerMapper.selectOne(customerEntity);

        customerEntity.setFullName(fullName);
        customerEntity.setLegalName(legalName);
        customerEntity.setAddress(address);
        customerEntity.setMobile(mobile);
        customerMapper.updateByPrimaryKey(customerEntity);
        return ResponseWrapper.succeed();
    }

    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public void register(String account, String password, String fullName, String legalName, String address, String mobile) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setAccount(account);
        customerEntity.setPassword(password);
        customerEntity.setFullName(fullName);
        customerEntity.setLegalName(legalName);
        customerEntity.setAddress(address);
        customerEntity.setMobile(mobile);
        customerEntity.setAccType(1);
        customerEntity.setAuthJson("{\n" +
                "  \"code\": 0\n" +
                "  ,\"msg\": \"\"\n" +
                "  ,\"data\": [{\n" +
                "    \"title\": \"数据统计\"\n" +
                "    ,\"icon\": \"layui-icon-home\"\n" +
                "    ,\"list\": [{\n" +
                "      \"title\": \"查看统计\"\n" +
                "      ,\"jump\": \"data/show\"\n" +
                "    }]\n" +
                "  },{\n" +
                "    \"title\": \"存储管理\"\n" +
                "    ,\"icon\": \"layui-icon-home\"\n" +
                "    ,\"list\": [{\n" +
                "      \"title\": \"图片管理\"\n" +
                "      ,\"jump\": \"goods/list\"\n" +
                "    },{\n" +
                "      \"title\": \"视频管理\"\n" +
                "      ,\"jump\": \"grade/list\"\n" +
                "    },{\n" +
                "      \"title\": \"文件管理\"\n" +
                "      ,\"jump\": \"grade/list\"\n" +
                "    },{\n" +
                "      \"title\": \"主页轮播图\"\n" +
                "      ,\"jump\": \"mainPage/get\"\n" +
                "    }]\n" +
                "  },{\n" +
                "    \"title\": \"服务器设置\"\n" +
                "    ,\"icon\": \"layui-icon-home\"\n" +
                "    ,\"list\": [{\n" +
                "      \"title\": \"用户列表\"\n" +
                "      ,\"jump\": \"myuser/list\"\n" +
                "    }]\n" +
                "  }]\n" +
                "}");
        customerMapper.insert(customerEntity);

    }
}
